/*
 * @Author: Crism
 * @Date: 2018-07-31 17:56:48
 * @LastEditors: Crism
 * @LastEditTime: 2018-08-10 15:22:49
 * @Description: 
 * @Email: crism@qq.com
 */

const HttpUtil = require('../util/HttpUtil');
const Utils = require('../util/Utils');
const CommomUtil = require('../libs/CommomUtil');
const cheerio = require('cheerio');
const Download = require('../util/Download');
const UploadImg = require('../util/UploadImg');
const db_wyw = require('../config').db_wyw;


module.exports.getAuthors = getAuthors;
module.exports.getAuthorInfo = getAuthorInfo;
module.exports.getAuthorDetail = getAuthorDetail;

async function getAuthors(html, indexId) {

    if (html) {
        let $ = cheerio.load(html, { decodeEntities: false });
        let ListContent = $('div.left');

        let authors = [];

        ListContent.find('div.cont').each(function (index, item) {
            let obj = $(this);
            let img = obj.find('div.divimg').find('img').attr('src');
            // Download.downloadImg(img);
            // UploadImg.uploadImg(img);
            authors.push({
                'author_id': 2018000000 + (indexId - 1) * 10 + index,
                'author_name': obj.find('p').find('a').find('b').text(),
                'author_img': img == undefined ? '' : img.slice(img.lastIndexOf('/') + 1),
                'author_intro': obj.find('p').next().text(),
                'author_detail_url': 'https://so.gushiwen.org' + obj.find('p').find('a').attr('href'),
                'author_poetic_url': obj.find('p').find('a').attr('href').slice(1),
            });
            // addAuthorColumn(authors[index]);
        });
        for (let i = 0; i < authors.length; i++) {
            let obj = await getAuthorDetail(authors[i].author_detail_url, authors[i].author_id);
            Object.assign(authors[i], obj);
        }
        return authors;
    } else {
        console.log('无数据传入！');
    }
}

async function getAuthorInfo() {
    let authors = await selectAuthors();
    if (authors) {
        for (let i = 0; i < authors.length; i++) {
            await getAuthorInfoss('https://so.gushiwen.org/' + authors[i].author_url, authors[i].author_id);
        }
    }
}

async function addAuthorColumn(author) {
    let author_name = db_wyw.escape(author.author_name);
    let author_dynasty = db_wyw.escape(author.author_dynasty);
    let author_portrait = db_wyw.escape(author.author_img);
    let author_intro = db_wyw.escape(author.author_intro);
    let sql = 'INSERT INTO author(author_name,author_dynasty,author_portrait,author_intro,author_url) ' +
        'VALUES(' + author_name + ',' + author_dynasty + ',' + author_portrait + ',' + author_intro + ',"' + author.author_poetic_url + '");';
    db_wyw.queryNum(sql);
}

async function addAuthorInfoColumn(authorInfo) {
    if (CommomUtil.isEmpty(authorInfo.detail_content) || authorInfo.detail_content == '暂无数据...') {
        return false;
    }
    let author_id = authorInfo.author_id;
    let detail_field = db_wyw.escape(authorInfo.detail_field);
    let detail_content = db_wyw.escape(authorInfo.detail_content);

    let sql = 'select count(*) a from author_info where author_id = ' + author_id + ' and detail_field=' + detail_field;
    let flag = await db_wyw.queryOne(sql);

    if (flag['a'] <= 0) {
        sql = 'INSERT INTO author_info(detail_field,detail_content,author_id) ' +
            'VALUES(' + detail_field + ',' + detail_content + ',' + author_id + ');';
    } else {
        sql = 'update author_info set detail_content = ' + detail_content + ' where author_id = ' + author_id + ' and detail_field=' + detail_field;
    }
    db_wyw.queryNum(sql);
}

async function selectAuthors() {
    let sql = 'SELECT author_id,author_url FROM author limit 1800,5000';
    let rows = await db_wyw.query(sql);
    if (rows instanceof Array && rows.length > 0) {
        return rows;
    } else {
        return [];
    }
}



async function getAuthorDetail(author_detail_url, author_id) {
    let html = await HttpUtil.httpGet(author_detail_url);
    if (html) {
        let $ = cheerio.load(html, { decodeEntities: false });
        let ListContent = $('div.left');

        let details = {};

        details['author_id'] = author_id;

        let str = [];
        let array = [];

        ListContent.find('div.contyishang').each(function (index, item) {
            let data = $(this);
            if ('展开阅读全文 ∨' == data.find('div').last().find('a').text()) {
                array[index] = data.find('div').last().find('a').attr('href').replace(/[^0-9]/ig, "");
                str[index] = data.find('h2').text();
            } else {
                str[index] = data.find('h2').text();
                let content = data.find('p').text();
                if (content.length < 4) {
                    data.find('div').remove();
                    content = data.text();
                }
                details[str[index]] = content;
            }
        });

        /** 上面的遍历方法是异步的 */
        for (let i = 0; i < str.length; i++) {
            if (array[i] != null) {
                let content = await getAuthorDesc(array[i], str[i]);
                details[str[i]] = CommomUtil.isEmpty(content) ? '暂无数据...' : content;
            }

            details['detail_field'] = str;
            details['detail_ids'] = array;

        }
        return details;
    } else {
        console.log('无数据传入！');
    }
}


async function getAuthorInfoss(author_detail_url, author_id) {
    let html = await HttpUtil.httpGet(author_detail_url);
    if (html) {
        let $ = cheerio.load(html, { decodeEntities: false });
        let ListContent = $('div.left');
        let str = [];
        let array = [];

        ListContent.find('div.contyishang').each(function (index, item) {
            let data = $(this);

            if ('展开阅读全文 ∨' == data.find('div').last().find('a').text()) {
                array[index] = data.find('div').last().find('a').attr('href').replace(/[^0-9]/ig, "");
                str[index] = data.find('h2').text();
            } else {

                str[index] = data.find('h2').text();
                let content = data.find('p').text();

                if (content.length < 4) {
                    data.find('div').remove();
                    content = data.text();
                }
                let authorm = {};
                authorm['author_id'] = author_id;
                authorm['detail_field'] = str[index];
                authorm['detail_content'] = content;
                addAuthorInfoColumn(authorm);
            }
        });

        for (let i = 0; i < str.length; i++) {
            if (array[i] != null) {
                let content = await getAuthorDesc(array[i], str[i]);
                let authorm = {};
                authorm['author_id'] = author_id;
                authorm['detail_field'] = str[i];
                authorm['detail_content'] = CommomUtil.isEmpty(content) ? '暂无数据...' : content;
                addAuthorInfoColumn(authorm);
            }
        }
    } else {
        console.log('无数据传入！');
    }
}


const descUrl = 'https://so.gushiwen.org/authors/ajaxziliao.aspx?id=';
async function getAuthorDesc(id, text, cnt = 0) {

    if (CommomUtil.isEmpty(id)) return null;
    let url = descUrl + id;
    while (cnt < 3) {
        let html = await HttpUtil.httpGet(url);
        cnt++;
        if (html) {
            let $ = cheerio.load(html, { decodeEntities: false });
            let recordData = $('div.contyishang');
            if (text == recordData.find('h2').text()) {
                let content = recordData.find('p').text();
                if (content.length < 4) {
                    recordData.find('div').remove();
                }
                return content.length < 10 ? recordData.text() : content;
            }
        }
    }

}
